package com.wangp.mywrite.s_netty.nio.ch3.nonblock_mode;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.wangp.mywrite.s_netty.nio.ch1.ByteBufferUtil.debugRead;

/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/16
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 使用 nio 理解阻塞模式，单线程.

        // 0. 创建byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        // 1. 创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 2. 绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 3. 建立一个链接的集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // 4. accept建立连接, socket channel 与客服端进行通信
            SocketChannel sc = serverSocketChannel.accept(); // 非阻塞，线程还会继续执行，如果没有建立连接,sc是null
            if (sc != null) {
                log.info("connected...{}", sc);
                sc.configureBlocking(false);// 非阻塞模式
                channels.add(sc);
            }
            // 5. 接受客户端发送的数据
            for (SocketChannel channel : channels) {
                int len = channel.read(byteBuffer);// 非阻塞，线程仍然继续运行，如果没有数据，read 返回 0
                if (len > 0) {
                    byteBuffer.flip();
                    debugRead(byteBuffer);
                    byteBuffer.clear();
                    log.info("after read...{}", channel);
                }
            }
        }
    }
}
